package com.tuanzi.loan.business.repository.statistics.impl;

import static com.tuanzi.loan.generated.jooq.stat.tables.StatExternalLoanArea.STAT_EXTERNAL_LOAN_AREA;
import static com.tuanzi.loan.generated.jooq.stat.tables.StatSms.STAT_SMS;

import org.jooq.impl.TableImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;

import com.tuanzi.loan.business.repository.statistics.custom.ExternalLoanAreaStatistisCustomRepository;
import com.tuanzi.loan.core.repository.JOOQBaseRepository;
import com.tuanzi.loan.vo.request.statistics.ExternalLoanAreaStatistisRequest;
import com.tuanzi.loan.vo.response.statistics.ExternalLoanAreaStatistisResponse;
import com.tuanzi.server.loan_base.util.DateUtils;

/**
* @author chenweijun 
* @version 2018年4月25日
*/
@SuppressWarnings({ "rawtypes" })
@Repository
public class ExternalLoanAreaStatistisRepositoryImpl extends JOOQBaseRepository implements ExternalLoanAreaStatistisCustomRepository{
	
	@Override
	protected TableImpl getTable() {
		return STAT_EXTERNAL_LOAN_AREA;
	}

	@Override
	public Page<ExternalLoanAreaStatistisResponse> list(ExternalLoanAreaStatistisRequest searchRequest,
			Pageable pageable) {
		
		fields(STAT_EXTERNAL_LOAN_AREA.fields());
		eq(STAT_EXTERNAL_LOAN_AREA.PRODUCT_ID, searchRequest.getProductId());
		between(STAT_EXTERNAL_LOAN_AREA.CREATE_DATE, 
				searchRequest.getUnionLoginStartDate() == null ? 
						searchRequest.getUnionLoginStartDate() : DateUtils.formatDateToYyyyMMdd(searchRequest.getUnionLoginStartDate()), 
				searchRequest.getUnionLoginEndDate() == null ? 
						searchRequest.getUnionLoginEndDate() : DateUtils.formatDateToYyyyMMdd(searchRequest.getUnionLoginEndDate()));
		orderBy(STAT_EXTERNAL_LOAN_AREA.CREATE_DATE, Sort.Direction.DESC);
		
		return search(pageable, record ->{
			ExternalLoanAreaStatistisResponse response = new ExternalLoanAreaStatistisResponse();
			response.setUnionLoginDate(record.get(STAT_EXTERNAL_LOAN_AREA.CREATE_DATE));
			response.setProductId(record.get(STAT_EXTERNAL_LOAN_AREA.PRODUCT_ID));
			response.setViewAreaUV(record.get(STAT_EXTERNAL_LOAN_AREA.VIEW_AREA_UV));
			response.setFirstUnionLoginCount(record.get(STAT_EXTERNAL_LOAN_AREA.FIRST_UNION_LOGIN_COUNT));
			response.setLoginCount(record.get(STAT_EXTERNAL_LOAN_AREA.LOGIN_COUNT));
			return response;
		});
	}

}
